package elitech.vietnam.weatherfashion.autoupdate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.config.Const;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

@SuppressLint("HandlerLeak")
public class CheckUpdate extends Activity {
	// auto update
	final int BEGIN_DOWNLOAD_UPDATE = 1;
	final int DOWNLOAD_UPDATE = 2;
	final int END_DOWNLOAD_UPDATE = 3;
	private int versionCode;
	private Integer size;
	private String ApkName;
	private String urlpath;
	private String PackageName;
	private ProgressDialog progressBar;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case BEGIN_DOWNLOAD_UPDATE:
				progressBar.show();
				break;
			case DOWNLOAD_UPDATE:
				Integer i = (Integer) msg.obj;
				progressBar.setProgress(i);
				break;
			case END_DOWNLOAD_UPDATE:
				progressBar.dismiss();
				break;
			default:
				break;
			}
		}

	}; // handler

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		Bundle b = getIntent().getExtras();
		if (b == null)
			finish();
		else {
			PackageName = "elitech.vietnam.weatherfashion".toString();
			ApkName = "WF Project.zip";
			String s = getResources().getString(R.string.loading) + "...";
			progressBar = new ProgressDialog(this);
			progressBar.setCancelable(false);
			progressBar.setMessage(s);
			progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			versionCode = b.getInt(Constants.VERSION_CODE);
			threadDownload.start();
		}
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	Thread threadDownload = new Thread(new Runnable() {
		public void run() {
			try {
				Message mes = handler.obtainMessage(BEGIN_DOWNLOAD_UPDATE);
				handler.sendMessage(mes);
				mes = null;
				// fLog.Write("Check autoupdate: DownloadOnSDcard");
				DownloadOnSDcard();
				mes = handler.obtainMessage(END_DOWNLOAD_UPDATE);
				handler.sendMessage(mes);
				mes = null;
				// fLog.Write("Check autoupdate: InstallApplication");
				InstallApplication();
				// fLog.Write("Check autoupdate: UnInstallApplication");
				// UnInstallApplication(PackageName.toString());
				finish();
			} catch (Exception e) {
				finish();
			}
		}
	});

	/**
	 * Download file form server to sdcard
	 * 
	 */
	public void DownloadOnSDcard() throws Exception {
		ApkName = "WF Project.zip";
		urlpath = "http://eli6.cafe24.com/AutoUpdateAndroid/Fashion/" + Const.COUNTRY_CODE+ "_WF_Project"
				+ versionCode + ".zip";
//		urlpath = "http://192.168.1.113/AutoUpdate_Fashion/" + AppConfig.COUNTRY_CODE+ "_WF_Project"
//				+ versionCode + ".zip";
		URL url = new URL(urlpath.toString()); // Your given URL.

		HttpURLConnection c = (HttpURLConnection) url.openConnection();
		c.setRequestMethod("GET");
		c.setDoOutput(true);
		c.connect(); // Connection Complete here.!
		// Toast.makeText(getApplicationContext(),
		// "HttpURLConnection complete.", Toast.LENGTH_SHORT).show();
		size = c.getContentLength();
		Integer total = 0;
		String PATH = Environment.getExternalStorageDirectory()
				+ "/download/WF Project/";
		File file = new File(PATH); // PATH = /mnt/sdcard/download/
		if (!file.exists()) {
			file.mkdirs();
		}
		File outputFile = new File(file, ApkName.toString());
		FileOutputStream fos = new FileOutputStream(outputFile);
		InputStream is = c.getInputStream(); // Get from Server and Catch In
												// Input Stream Object.
		byte[] buffer = new byte[1024];
		int len1 = 0;

		Message mes;// = handler

		while ((len1 = is.read(buffer)) != -1) {
			total += len1;
			mes = handler.obtainMessage(DOWNLOAD_UPDATE, (total * 100) / size);
			handler.sendMessage(mes);
			mes = null;
			fos.write(buffer, 0, len1); // Write In FileOutputStream.
		}
		fos.close();
		is.close();
		c.disconnect();
		// Unzip
		ZipUtility.unzip(outputFile, file);
		outputFile.delete();
	}

	public void InstallApplication() {
		Uri packageURI = Uri.parse(PackageName.toString());
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
				packageURI);
		intent.setDataAndType(
				Uri.fromFile(new File(Environment.getExternalStorageDirectory()
						+ "/download/WF Project/WF Project.apk")),
				"application/vnd.android.package-archive");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);

	}

	public void UnInstallApplication(String packageName)// Specific package Name
														// Uninstall.
	{
		// Uri packageURI = Uri.parse("package:com.CheckInstallApp");
		Uri packageURI = Uri.parse(packageName.toString());
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		startActivity(uninstallIntent);
	}

}